package com.systop.tea.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.systop.tea.common.R;
import com.systop.tea.entity.Article;
import com.systop.tea.service.ArticleService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequiredArgsConstructor
@RequestMapping("/article")
public class ArticleController {

    private final ArticleService articleService;

    @GetMapping("/query")
    public R<Page> query(Article article, Integer pageNum, Integer pageSize) {
        Page page = new Page(pageNum, pageSize);
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(article.getArticleTitle()), Article::getArticleTitle, article.getArticleTitle());
        articleService.page(page, queryWrapper);
        return R.success(page);
    }

    @GetMapping("/{id}")
    public R<Article> queryById(@PathVariable Integer id) {
        Article article = articleService.getById(id);
        return R.success(article);
    }

    @PostMapping
    public R<String> add(@RequestBody Article article) {
        article.setArticleDate(LocalDateTime.now());
        boolean row = articleService.save(article);
        if (row) {
            return R.success("添加成功");
        } else {
            return R.error("添加失败");
        }
    }

    @PutMapping
    public R<String> edit(@RequestBody Article article) {
        boolean row = articleService.updateById(article);
        if (row) {
            return R.success("修改成功");
        } else {
            return R.error("修改失败");
        }
    }

    @DeleteMapping("/{id}")
    public R<String> delete(@PathVariable Integer id) {
        boolean row = articleService.removeById(id);
        if (row) {
            return R.success("删除成功");
        } else {
            return R.error("删除失败");
        }
    }

}
